package services

import (
	"supershare/backend/models"
	"time"
)

// BaseService 基础服务，提供通用方法
type BaseService struct{}

// PaginationParams 分页参数
type PaginationParams struct {
	Page     int
	PageSize int
}

// FilterParams 过滤参数
type FilterParams struct {
	StoreId int64
	Status  int
	Title   string
	StartTime int64
	EndTime   int64
}

// BuildFilters 构建过滤条件
func (s *BaseService) BuildFilters(params FilterParams) map[string]interface{} {
	filters := make(map[string]interface{})
	
	if params.StoreId > 0 {
		filters["store_id"] = params.StoreId
	}
	if params.Status != -1 {
		filters["status"] = params.Status
	}
	if params.Title != "" {
		filters["title"] = params.Title
	}
	if params.StartTime > 0 {
		filters["start_time"] = params.StartTime
	}
	if params.EndTime > 0 {
		filters["end_time"] = params.EndTime
	}
	
	return filters
}

// BuildTimeFilters 构建时间过滤条件
func (s *BaseService) BuildTimeFilters(startTimeStr, endTimeStr string) map[string]interface{} {
	filters := make(map[string]interface{})
	
	if startTimeStr != "" {
		if startTime, err := time.ParseInLocation("2006-01-02", startTimeStr, time.Local); err == nil {
			filters["start_time"] = startTime
		}
	}
	
	if endTimeStr != "" {
		if endTime, err := time.ParseInLocation("2006-01-02", endTimeStr, time.Local); err == nil {
			// 将结束时间设置为当天的23:59:59
			endTime = endTime.Add(24*time.Hour - time.Second)
			filters["end_time"] = endTime
		}
	}
	
	return filters
}

// BuildPagination 构建分页参数
func (s *BaseService) BuildPagination(page, pageSize int) PaginationParams {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}
	return PaginationParams{
		Page:     page,
		PageSize: pageSize,
	}
}

// CheckStoreExists 检查门店是否存在
func (s *BaseService) CheckStoreExists(storeId int64) (bool, error) {
	store, err := models.GetStoreById(storeId)
	if err != nil {
		return false, err
	}
	return store != nil, nil
}

// CheckMeituanConfigExists 检查美团配置是否存在
func (s *BaseService) CheckMeituanConfigExists(storeId int64) (bool, error) {
	config, err := models.GetMeituanByStoreId(storeId)
	if err != nil {
		return false, err
	}
	return config != nil, nil
}

// CheckMeituanGroupExists 检查美团团购活动是否存在
func (s *BaseService) CheckMeituanGroupExists(id int64) (bool, error) {
	group, err := models.GetMeituanGroupById(id)
	if err != nil {
		return false, err
	}
	return group != nil, nil
}